import json
import re
from datetime import datetime

class LiteratureReview:
    def __init__(self, topic):
        self.topic = topic # 主题
        self.topic_type = None # 主题类型
        self.structure = None # 大纲
        self.content = {} # 小节内容
        self.references = [] # 参考文献
        self.lit_review = "" # 文献综述
        self.file_name = "" # 文献综述保存地址

    def combine_title_content(self, data):
        """将标题和内容组合成文本块"""
        text_blocks = []
        for item in data.values():
            title = item.get('paper_title', '')
            content = item.get('chunk_text', '')
            if title and content:
                text_block = f"{title}\n\n{content}"
                text_blocks.append(text_block)
        return text_blocks

    # 将Json结构大纲转换为markdown####废弃掉###
    def structure_to_md_old(self,structure):
        # 首先将字符串解析为JSON对象
        try:
            if isinstance(structure, str):
                structure = json.loads(structure)
                
            md = f"# {structure['title']}\n"
            
            for section in structure['sections']:
                md += f"\n## {section['section_title']}\n"
                
                if 'sub_sections' in section:
                    for sub_section in section['sub_sections']:
                        md += f"### {sub_section['sub_section_title']}\n"
                        
            return md
        except Exception as e:
            print(f"Error converting structure to markdown: {str(e)}")
            return ""
    

    def add_numbering_to_structure(self,structure_str):
        """
        为结构化数据中的章节和子章节添加编号。
        
        Args:
            structure_str (str): 结构化的输入数据，以字符串形式表示。
            
        Returns:
            dict: 添加了编号的结构化数据。
        """
        # 解析 JSON 字符串为字典
        structure = json.loads(structure_str)

        def process_sections(sections, prefix=""):
            for index, section in enumerate(sections, start=1):
                # 生成当前章节的编号
                current_number = f"{prefix}{index}"
                # 更新当前章节的标题
                section['section_title'] = f"{current_number} {section['section_title']}"
                # 处理子章节
                if 'sub_sections' in section:
                    process_sub_sections(section['sub_sections'], prefix=f"{current_number}.")

        def process_sub_sections(sub_sections, prefix):
            for sub_index, sub_section in enumerate(sub_sections, start=1):
                # 生成当前子章节的编号
                current_number = f"{prefix}{sub_index}"
                # 更新当前子章节的标题
                sub_section['sub_section_title'] = f"{current_number} {sub_section['sub_section_title']}"

        # 处理顶层 sections
        process_sections(structure['sections'])

        return structure


    def structure_to_md(self, structure):
        """
        将结构化数据转换为带有数字编号的Markdown格式。
        
        Args:
            structure (str): 结构化的输入数据，以字符串形式表示。
            
        Returns:
            str: 转换后的带有数字编号的Markdown格式字符串。
        """
        # 解析传入的字符串结构
        try:
            # 如果输入是字符串，则转换为字典格式
            if isinstance(structure, str):
                structure = json.loads(structure)

            # 获取标题
            md = f"# {structure['title']}\n"

            # 遍历顶层的 sections
            for section_index, section in enumerate(structure['sections'], start=1):
                # 顶层章节编号
                md += f"## {section_index} {section['section_title']}\n"

                # 遍历子章节
                for sub_index, sub_section in enumerate(section.get('sub_sections', []), start=1):
                    # 子章节编号
                    md += f"### {section_index}.{sub_index} {sub_section['sub_section_title']}\n"

            return md

        except json.JSONDecodeError:
            return "Invalid JSON structure"

    # 将Json结构大纲转换为列表
    def structure_to_list(self,structure):
        # 将结构解析为列表形式
        try:
            if isinstance(structure, str):
                structure = json.loads(structure)
                
            result = []
            # 添加标题
            title = structure['title']
            
            # 添加章节标题
            for section in structure['sections']:
                section_title = section['section_title']
                
                # 添加子章节标题
                if 'sub_sections' in section:
                    for sub_section in section['sub_sections']:
                        sub_section_title = sub_section['sub_section_title']
                        result.append(
                            {
                            "title":title,
                            "section_title":section_title,
                            "sub_section_title":sub_section_title
                            }
                        )
                        
            return result
        except Exception as e:
            print(f"Error converting structure to list: {str(e)}")
            return []
        
    def content_to_LitReview(self):
        """将内容转换为LitReview对象"""
        md_output = ""
        current_title = ""
        current_section = ""
        current_reference_number = 1
        reference_list = []
        data = self.structure_to_list(self.structure)

        index = 1
        for item in data:
            title = item['title']
            section_title = item['section_title']
            sub_section_title = item['sub_section_title']

            if title != current_title:
                md_output += f"# {title}\n"
                current_title = title

            if section_title != current_section:
                md_output += f"\n## {section_title}\n"
                current_section = section_title

            md_output += f"\n### {sub_section_title}\n"
            sub_section_title_result = re.sub(r'^\d+(\.\d+)*\s*', '', sub_section_title)
            content = self.content[sub_section_title_result]['content']### 修改此处sub_section_title为sub_section_title_result            
            #content = self.content[sub_section_title]['content']
            reference = self.content[sub_section_title_result]['reference']### 修改此处sub_section_title为sub_section_title_result
            content, reference, current_reference_number = self.format_content_reference(content, reference, current_reference_number)
            reference_list.extend(reference)
            # 将内容中的空行合并为单个空行  
            content = re.sub(r'\n{2,}', '\n', content)
            md_output += f"{content}"
        
        reference_list = sorted(reference_list, key=self.extract_number)
        reference = "\n## Reference\n" + '\n'.join(reference_list)

        self.lit_review = md_output + reference
    
    def extract_number(self, s):
        match = re.search(r'\[(\d+)\]', s)  # 使用正则表达式提取 [数字]
        if match:
            return int(match.group(1))  # 返回提取的数字并转换为整数
        return 0  # 如果没有找到数字，返回 0（或其他默认值）

    def format_content_reference(self, content, reference, current_reference_number):
        """将内容和参考文献格式化"""
        # 创建一个字典来存储旧引用编号到新引用编号的映射
        ref_mapping = {}
        
        # 找出所有的引用编号
        citations = re.findall(r'<sup>(\d+)</sup>', content)
        
        # 为每个唯一的引用编号分配新编号
        for old_num in citations:
            if old_num not in ref_mapping:
                ref_mapping[old_num] = current_reference_number
                current_reference_number += 1

        # 替换内容中的引用编号。使用newsup标签，表示为新标签，防止被后面标签覆盖
        for old_num, new_num in ref_mapping.items():
            content = content.replace(f'<sup>{old_num}</sup>', f'<newsup>{new_num}</newsup>')
        content = content.replace("<newsup>","<sup>")
        content = content.replace("</newsup>", "</sup>")

        # 更新reference列表，保持与新编号的对应关系
        new_reference = []
        for _, value in enumerate(reference):
            index = re.findall(r'\[(\d+)\]', value)[0]
            if index in ref_mapping:
                ref = value.replace(f'[{index}]', f'[{ref_mapping[str(index)]}]')
                new_reference.append(ref)
                
        return content, new_reference, current_reference_number
    
    def LitReview_to_md(self, path):
        # 获取当前时间
        current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

        # 文件路径
        topic = self.topic
        topic = topic.replace(" ", "_")
        topic = topic.replace(":", "：")
        topic = topic.replace("?", ".")
        file_path = path+f"{topic}_{current_time}.md"

        # 写入Markdown文件
        with open(file_path, "w", encoding="utf-8") as md_file:
            md_file.write(self.lit_review)
        self.file_name = file_path

        return file_path

        
    def add_section(self, section_title, content):
        self.content[section_title] = content

    def add_reference(self, reference):
        self.references.append(reference)
        
    def set_structure(self, structure):
        self.structure = structure

    def set_topic_type(self, topic_type):
        self.topic_type = topic_type

    def set_content(self, content):
        self.content = content

    def set_references(self, references):
        self.references = references
